#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import time
import os
import signal
from subprocess import Popen, CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP
from process_utils.win32 import get_pid_by_exec_name
from mj_parser import common_errors
from mj_parser.win32 import win32_command
import Lib.Logger.log4py as logging


class AudiSourceETK:
    def __init__(self, root_dir="."):
        print("ETK Parser started")
        self.root_dir = root_dir
        self.conf_file = os.path.join(root_dir, "conf", "etka.conf")
        self.controller_path = os.path.join(root_dir, "bin", "etka.exe")
        self.data_path = os.path.join(root_dir, "data")
        self.repo_path = os.path.join(self.data_path, "repository")

        self.supported = ['audi', 'fawvw', 'svwvw', 'vw', 'svwsk', 'skoda']
        self.logger = logging.get_logger("crawler", "AudiSourceETK")

        self.etka_proc = None
        self.certserver_proc = None
        self.etka_conf = self.read_config()
        self.run_certserver()
        self.run_etka()


    def read_config(self):
        result = {
            'ETKA_EXE': 'EtStart.exe',
            'ETKA_PATH': 'D:\\ETKA\\PROG',
            'ETKA_ARGS': 'D:\\ETKA\PROG\\ETKA_VW.INI'

        }

        with open(self.conf_file) as fi:
            for line in fi:
                tokens = line.split('=')
                if len(tokens) == 1:
                    continue
                result[tokens[0]] = tokens[1].strip('\r').strip('\n')
        return result

    def run_certserver(self):
        if self.certserver_proc is not None:
            self.certserver_proc.terminate()

        executable = os.path.join(self.root_dir, "bin", "CertServer.exe")
        args = [executable]
        self.certserver_proc = Popen(args, cwd=self.root_dir, creationflags=CREATE_NEW_CONSOLE)

    def run_etka(self):
        pid_list = get_pid_by_exec_name("Etka7.exe")
        for pid in pid_list:
            os.kill(pid, signal.SIGTERM)

        executable = os.path.join(self.etka_conf['ETKA_PATH'], self.etka_conf['ETKA_EXE'])
        self.logger.info("running {0}".format(executable))
        args = [executable, self.etka_conf['ETKA_ARGS']]
        self.etka_proc = Popen(args, cwd=self.etka_conf['ETKA_PATH'], creationflags=CREATE_NEW_PROCESS_GROUP)
        time.sleep(10)

    def get_data(self, str_vin, brand, group):
        if brand not in self.supported:
            return common_errors.ERR_NOT_SUPPORTED_BRAND, None

        try:
            win32_command('{0} {1}'.format(self.controller_path, str_vin))

            res = self.parser_cmd_result()

            if res is None:
                return common_errors.ERR_UNKNOWN, None

            if '98' == res:
                return common_errors.ERR_CORRUPT_ETKA, None

            response_list = res.split('_')
            if response_list[0] != '0':
                print(response_list[0])
                return str(response_list[0]).replace('\n', ''), None

            filename = os.path.join(self.repo_path, '{0}.xml'.format(str_vin))
            if not os.path.exists(filename):
                time.sleep(5)
            return common_errors.ERR_SUCCESS, filename

        except Exception as ex:
            self.logger.error('get_config_data exception :: ' + str(ex))
        return common_errors.ERR_UNKNOWN, None

    def parser_cmd_result(self):
        try:
            filename = os.path.join(self.data_path, "Context.TMP")
            fobj = open(filename, encoding='utf_8_sig')
            con = fobj.read()
            fobj.close()
            os.remove(filename)
            return con
        except Exception as ex:
            self.logger.error(ex)
        return None
